import {IRequestOptions, InterceptorManager, httpRequest} from './fetch';

// 创建拦截器管理器实例
const requestInterceptorManager: InterceptorManager<IRequestOptions> = new InterceptorManager<IRequestOptions>();
// 添加拦截器
requestInterceptorManager.use(
    {
        onFulfilled: (options) => {
            const authorization = request.AUTHORIZATION;
            if (authorization) {
                options.headers.Authorization = authorization;
            }
            return options;
        }
    }
);

// 定义响应拦截器
const responseInterceptorManager: InterceptorManager<any> = new InterceptorManager<any>();
responseInterceptorManager.use({
    onFulfilled: async (response) => {
        //系统定义异常
        if (!response.ok) {
            throw response;
        }
        let responseData = await response.json();
        if (
            responseData.content.httpcode &&
            responseData.content.httpcode === 302) {
            return responseData
        }
        return responseData.content;
    },
    onRejected: async (error) => {
        // 服务器异常
        if(!error.status){
            throw {message:"服务器访问失败",content:error.message};
        }
        //系统定义异常
        if (error.status === 403) {
            let errObj = await error.json()
            throw {message:errObj.content.defaultMessage,content:errObj.message};
        }
        if (error.status === 520) {
            let errObj = await error.json()
            throw {message:errObj.message,content:errObj.content.defaultMessage};
        }
        if (error.status === 521) {
            let errObj = await error.json()
            throw {message:errObj.message,content:errObj.content.errors};
        }
    },
});

export const request = {
    //BaseURL
    HOST: 'http://127.0.0.1:8080',
    //用户凭证
    AUTHORIZATION: '',
    //超时
    TIME_OUT: 10000,

    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json;charset=UTF-8',
        Connection: 'keep-alive',
    },
    //get请求
    get(api, params) {
        return httpRequest({
            method: 'GET',
            headers: this.headers,
            url: this.HOST + api,
            param: params
        }, requestInterceptorManager, responseInterceptorManager);
    },
    //post请求
    post(api, params) {
        return httpRequest({
            method: 'POST',
            headers: this.headers,
            url: this.HOST + api,
            param: params
        }, requestInterceptorManager, responseInterceptorManager);
    },
    //put请求
    put(api, params) {
        return httpRequest({
            method: 'PUT',
            headers: this.headers,
            url: this.HOST + api,
            param: params
        }, requestInterceptorManager, responseInterceptorManager);
    },
    //delete请求
    del(api) {
        return httpRequest({
            method: 'DELETE',
            headers: this.headers,
            url: this.HOST + api,
        }, requestInterceptorManager, responseInterceptorManager);
    },
};
